package com.nidu.demo.web.system;

import com.alibaba.cola.dto.PageResponse;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson2.JSONArray;
import com.nidu.demo.base.BatchDeleteCmd;
import com.nidu.demo.log.api.SysLoginLogService;
import com.nidu.demo.log.dto.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;

/**
 * 登录日志管理
 *
 * @author auto
 */
@Tag(name = "管理后台 - 登录日志")
@RestController
@RequestMapping("/system/login-log")
@Validated
@RequiredArgsConstructor
public class SysLoginLogController {

    private final SysLoginLogService loginLogService;

    @Operation(summary = "获取登录日志详情", description = "根据 ID 获取登录日志详细信息")
    @GetMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('system:login-log:query')")
    public SingleResponse<LoginLogCO> getLoginLogById(@PathVariable Long id) {
        return loginLogService.getById(id);
    }

    @Operation(summary = "分页查询登录日志", description = "分页获取登录日志信息")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermission('system:login-log:query')")
    public PageResponse<LoginLogCO> pageLoginLogs(LoginLogPageQry qry) {
        return loginLogService.page(qry);
    }

    @Operation(summary = "删除登录日志", description = "根据 ID 删除登录日志")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('system:login-log:delete')")
    public Response deleteLoginLog(@PathVariable Long id) {
        return loginLogService.delete(id);
    }

    @Operation(summary = "批量删除登录日志", description = "根据 ID 列表删除多个登录日志")
    @PostMapping("/batch-delete")
    @PreAuthorize("@ss.hasPermission('system:login-log:delete')")
    public Response deleteLoginLogs(@RequestBody BatchDeleteCmd cmd) {
        List<Long> ids = JSONArray.parseArray(cmd.getDelete(), Long.class);
        return loginLogService.delete(new HashSet<>(ids));
    }

    @Operation(summary = "清空登录日志", description = "清空所有登录日志")
    @PostMapping("/clear")
    @PreAuthorize("@ss.hasPermission('system:login-log:delete')")
    public Response clearLoginLogs() {
        return loginLogService.clear();
    }

    @Operation(summary = "导出登录日志", description = "导出登录日志到Excel")
    @PostMapping("/export")
    @PreAuthorize("@ss.hasPermission('system:login-log:export')")
    public Response exportLoginLogs(@RequestBody LoginLogPageQry qry) {
        return loginLogService.export(qry);
    }

}
